package com.example.shiyun.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.example.shiyun.R;
import com.example.shiyun.UI.Index;
import com.example.shiyun.Util.Util;
import com.example.shiyun.Util.Util_Okhttp;
import com.lwj.widget.loadingdialog.LoadingDialog;
import com.lwj.widget.loadingdialog.SimpleLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

/**
 * 引导页fragment
 */

public class PageFragment extends Fragment {
    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle args = getArguments();
        int index = args.getInt("index");
        int layoutId = args.getInt("layoutId");
        int count = args.getInt("count");
        rootView = inflater.inflate(layoutId, null);
        //EventBus注册，防止多次注册
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //初始化数据库
        LitePal.initialize(getContext());
        LitePal.getDatabase();

        // 滑动到最后一页有点击事件
        if (index == count - 1) {
            rootView.findViewById(R.id.id_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //初始化数据库
                    Util_Okhttp.ok_get("101010100");
                    //添加等待框
                    SimpleLoadingDialog simpleLoadingDialog=new SimpleLoadingDialog(getContext());
                    simpleLoadingDialog.showFirst("初始化......");
                    simpleLoadingDialog.showResult("加载中......");
                    simpleLoadingDialog.dismissDelay(2500, new LoadingDialog.DismissDelayEndCallback() {
                        @Override
                        public void onEnd(LoadingDialog dialog) {
                            startActivity(new Intent(getActivity(), Index.class));
                            getActivity().finish();
                        }
                    });

                }
            });
        }

        return rootView;
    }
    //接收EventBus传来的数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void r_data(String data)
    {
        //初始化数据库数据
            Util.litepal_data(data);
            Util_Okhttp.ok_get_Sentence();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //EventBus卸载
        EventBus.getDefault().unregister(this);
    }

}
